<template>
  <div class='container'>
    <el-dialog 
      class="assign-role" 
      :title="listForm.id ? '修改' : '新增'" 
      :visible="showaddDialog"
      @close="addClose"
      >
      <template #default>
        <el-form :model="listForm" :rules="listrules" ref="list" label-width="100px" class="demo-ruleForm">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input v-model="listForm.subjectName" placeholder="请输入学科名称"></el-input>
          </el-form-item>
          <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch 
            v-model="listForm.isFrontDisplay" 
            active-color="#13ce66"
            inactive-color="#ff4949"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button size="small" @click="addClose">取消</el-button>
        <el-button type="primary" size="small" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {add, update, detail} from '@/api/hmmm/subjects.js'
export default {
  name: 'addsubjects',
  props: {
    showaddDialog: {
      type: Boolean,
    }
  },
  data() {
    return {
      listForm: {
        subjectName: '',
        isFrontDisplay: true,
      },
      listrules: {
        subjectName:[
          { required: true, message: '请输入学科名称', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    async fetchDg(data) {
      const res = await detail(data)
      this.listForm = res.data
      this.listForm.isFrontDisplay = Boolean(res.data.isFrontDisplay)
    },
    addClose() {
      this.$emit('close-Dialog')
      this.listForm = {
        subjectName: '',
        isFrontDisplay: true
      }
      this.$refs.list.resetFields()
    },
    // 确定按钮表单校验
    confirm() {
      this.$refs.list.validate(async(valid) => {
        if(valid) {
          // 在点击确定的时候 区分当前是修改还是新增 再调接口
          if(this.listForm.id) {
            // 调用更新接口
            await update(this.listForm)
          } else {
            // 调用添加接口
            await add(this.listForm)
          }
          
          // 提示用户
          this.$message.success(this.listForm.id ? '修改成功' : '添加成功')
          // 关闭弹窗
          this.addClose()
          // 刷新页面
          this.$emit('update-list')
          // console.log(this.listForm)
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
